<?php

function clean($string){
    $string = str_replace('http://', '', $string);
    if(substr($string, -1) === '/') $string = substr ($string, 0, -1);
    return $string;
}

// récupération des données en cours ou par defaut
if(file_exists(CONFIG_PATH.'config_tmp.ini')){
    $datas = parse_ini_file(CONFIG_PATH.'config_tmp.ini',true);
}elseif(file_exists(CONFIG_PATH.'config_default.ini')){
    $datas = parse_ini_file(CONFIG_PATH.'config_default.ini',true);
}

// passer creation de compte
if(isset($_POST)&&isset($_POST['submit_end'])){
    $_POST['submit'] = $_POST['submit_end'];
    $step = 6;
}else{
    $step = (isset($_GET)&&isset($_GET['step'])&&$_GET['step']>0)?$_GET['step']+0:1;
}
$submitLabel = 'étape '.($step+1);
    
if(isset($_POST)&&isset($_POST['submit'])){ // sauvegarde des données en tmp
    // creation user admin
    
    if(isset($_GET)&&isset($_GET['create_user'])&&$_GET['create_user']==1){
        $user = new modele_user();
        $dataUser = array(
            'nom' => $_POST['nom']
            ,'prenom' => $_POST['prenom']
            ,'email' => $_POST['email']
            ,'mdp' => modele_user::encodePW($_POST['mdp'])
            ,'user_level_id'=>1
        );
        $user->setDatas($dataUser);
        $user->save();
        $user->autoLoginAdmin();
    }
    //
    $datas['domaine']['siteName'] = $_POST['domaine_siteName'];
    $datas['domaine']['baseURL'] = 'http://'.$_POST['domaine_baseURL'].'/';
    $datas['domaine']['baseDirectory'] = ($_POST['domaine_baseDirectory']!=='')?$_POST['domaine_baseDirectory'].'/':'';
    
    // modification du rewrite
    $stringReWrite = "<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /".$datas['domaine']['baseDirectory']."
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /".$datas['domaine']['baseDirectory']."index.php [L]
</IfModule>";
    $fileHtaccess = ADMIN_PATH.'../.htaccess';
    $handle = fopen($fileHtaccess,"w+");
    fwrite($handle, $stringReWrite);
    fclose($handle);
    
    $datas['google']['code_analytics'] = $_POST['google_code_analytics'];
    
    if($_POST['submit']==='Installer la base'){
        //verification installation ou update tables
        //
        // installation de la base de données
        $file = ADMIN_PATH.'install/pwe_project.sql';
        if(file_exists($file)){
            $contentString = file_get_contents($file);
            $contentString = str_replace(array('[[dbname]]','[[prefix]]'), array($_POST['bdd_database_name'],$_POST['bdd_database_prefix']), $contentString);
            bdd_sql::installDataBase($_POST['bdd_server'], $_POST['bdd_username'],$_POST['bdd_password'],$_POST['bdd_database_name'],$contentString);
        }
    }
    
    $datas['bdd']['server'] = $_POST['bdd_server'];
    $datas['bdd']['username'] = $_POST['bdd_username'];
    $datas['bdd']['password'] = $_POST['bdd_password'];
    $datas['bdd']['database_name'] = $_POST['bdd_database_name'];
    $datas['bdd']['database_prefix'] = $_POST['bdd_database_prefix'];
    
    $datas['design']['theme'] = $_POST['design_theme'];
    $datas['design']['theme_ui'] = $_POST['design_theme_ui'];
        
    $datas['admin']['name'] = $_POST['admin_name'];
    $datas['admin']['mail'] = $_POST['admin_mail'];
    $datas['contact']['name'] = $_POST['contact_name'];
    $datas['contact']['mail'] = $_POST['contact_mail'];
    $datas['support']['name'] = $_POST['support_name'];
    $datas['support']['mail'] = $_POST['support_mail'];
    $datas['service']['name'] = $_POST['service_name'];
    $datas['service']['mail'] = $_POST['service_mail'];
        
    $config_ini = '';
    foreach($datas as $rub=>$content){
        $config_ini .= '['.$rub.']'."\n";
        foreach($content as $k=>$v){
            $config_ini .= $k.' = "'.$v.'"'."\n";
        }
    }
    
    $handle = fopen(CONFIG_PATH.'config_tmp.ini',"w+");
    fwrite($handle, $config_ini);
    fclose($handle);
    
    // enregistrement définitif
    if($step===6){
        $newName = (DEBUG_MODE)?'config_local.ini':'config.ini';
        copy(CONFIG_PATH.'config_tmp.ini', CONFIG_PATH.$newName);
        chmod(CONFIG_PATH.$newName, 0755);
    }    
}

// matching des données du .ini dans le formulaire
if(isset($datas)&&$step<5){
    foreach($datas as $rub=>$content){
        foreach($content as $k=>$v){
            $_POST[$rub.'_'.$k] = clean($v);
        }
    }
}
?>
<?php if($step===2): ?>
<script>
$(document).ready(function(){
    checkDataBase();
});
</script>
<?php elseif($step===5): ?>
<style>
    div.validatError{
        position: absolute;
        padding: 7px;
        margin: 0 0 0 5px;
        background-color: #FFFFFF;
        border: thin solid #FF0000;
    }
</style>
<script>
$(document).ready(function(){
    var validatorForm = $('#form_user').validate({
        rules:{
            nom:'required'
            ,email:{
                required:true,
                email:true
            }
            ,mdp:'required'
        }
        ,messages:{
            email:{
                required:'Votre email est obligatoire'
                ,email:'Indiquez une adresse email valide'
            }
            ,nom:'Votre nom est obligatoire'
            ,mdp:'indiquez un mot de passe'           
        }
        ,submitHandler: function(form){
            form.submit();
        }
        ,invalidHandler: function(){
            $('div.validatError').remove();
        }
        ,focusInvalid: false
        ,errorElement: "div"
        ,errorClass: "validatError"
        ,errorPlacement: function(error, element) {
            if($('div#error'+element.attr('name'))){
                $('div#error'+element.attr('name')).remove();
            }
            $('body').append(error);
            var offset = element.offset();
            error.attr('id','error'+element.attr('name'));
            error.css('left', offset.left + element.outerWidth());
            error.css('top', offset.top);
            error.click(function(){
                $(this).fadeOut('fast');
                $(this).remove();
            });
        }
    });
    $("input").focus(function() {
        $('div#error' + $(this).attr("name")).remove();
    });
});
</script>
<?php endif; ?>
<form <?php echo ($step===5)?'id="form_user"':''; ?> method="post" enctype="multipart/form-data" action="?step=<?php echo $step+1; ?><?php echo ($step===5)?'&create_user=1':''; ?>">
    <div class="columns thirteen" <?php echo ($step===1)?'':'style="display: none;"'; ?>>
        <h2>&Eacute;tape 1 : Information Générale</h2>
        <p>nom du site :</p><input type="text" name="domaine_siteName" value="<?php echo (isset($_POST)&&isset($_POST['domaine_siteName']))?$_POST['domaine_siteName']:''; ?>"/><br/>
        <p>nom de domaine : </p>http://<input type="text" name="domaine_baseURL" value="<?php echo (isset($_POST)&&isset($_POST['domaine_baseURL']))?$_POST['domaine_baseURL']:''; ?>"/>/<br/>
        <p>répertoire d'installation : </p><input type="text" name="domaine_baseDirectory" value="<?php echo (isset($_POST)&&isset($_POST['domaine_baseDirectory']))?$_POST['domaine_baseDirectory']:''; ?>"/>/<br/>
        <br/>
        <p>Google Analytics :</p><input type="text" name="google_code_analytics" value="<?php echo (isset($_POST)&&isset($_POST['google_code_analytics']))?$_POST['google_code_analytics']:''; ?>"/>
        <p>
            <input class="pwe-ui-btn" type="submit" name="submit" value="<?php echo $submitLabel; ?>" />
        </p>
    </div>

    <div class="columns thirteen" <?php echo ($step===2)?'':'style="display: none;"'; ?>>
        <h2>&Eacute;tape 2 : Base de données</h2>
        <p>serveur : </p><input type="text" class="checkBdd" id="bdd_server" name="bdd_server" value="<?php echo (isset($_POST)&&isset($_POST['bdd_server']))?$_POST['bdd_server']:''; ?>"/><br/>
        <p>nom d'utilisateur : </p><input type="text" class="checkBdd" id="bdd_username" name="bdd_username" value="<?php echo (isset($_POST)&&isset($_POST['bdd_username']))?$_POST['bdd_username']:''; ?>"/><br/>
        <p>mot de passe : </p><input type="password" class="checkBdd" id="bdd_password" name="bdd_password" value="<?php echo (isset($_POST)&&isset($_POST['bdd_password']))?$_POST['bdd_password']:''; ?>"/><br/>
        <p>nom de la base : </p><input type="text" class="checkBdd" id="bdd_database_name" name="bdd_database_name" value="<?php echo (isset($_POST)&&isset($_POST['bdd_database_name']))?$_POST['bdd_database_name']:''; ?>"/><br/>
        <p>prefix de table : </p><input type="text" class="checkBdd" id="bdd_database_prefix" name="bdd_database_prefix" value="<?php echo (isset($_POST)&&isset($_POST['bdd_database_prefix']))?$_POST['bdd_database_prefix']:''; ?>"/>
        <p id="error_serveur" class="error"></p>
        <p>
            <a href="?step=<?php echo $step-1; ?>" class="pwe-ui-btn">précédent</a> 
            <input id="save_bdd" class="pwe-ui-btn" type="submit" name="submit" value="Installer la base" style="display: none;"/>
            <input id="bdd_ok" class="pwe-ui-btn" type="submit" name="submit" value="<?php echo $submitLabel; ?>" style="display: none;"/>
        </p>
    </div>

    <div class="columns thirteen" <?php echo ($step===3)?'':'style="display: none;"'; ?>>
        <h2>&Eacute;tape 3 : Thèmes graphiques</h2>
        thème du site :
        <select name="design_theme">
            <option value="default">default</option>
            <?php
            if($handle = opendir('../themes')){
                while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != ".." && !is_file('../themes/'.$entry)){
                        if($entry!=='default'){
                            $selected = (isset($_POST) && isset($_POST['design_theme']) && $entry === $_POST['design_theme'])?' selected="selected"':'';
                            echo "\t".'<option value="'.$entry.'"'.$selected.'>'.$entry.'</option>'."\r\n";
                        }
                    }
                }
                closedir($handle);
            }
            ?>
        </select><br/>
        thème du backoffice :
        <select name="design_theme_ui">
            <?php
            if($handle = opendir('../css/themes')){
                $currentTheme = (isset($_POST) && isset($_POST['design_theme_ui']))?$_POST['design_theme_ui']:THEME_UI_DEFAULT;
                while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != ".." && !is_file('../css/themes/'.$entry)) {
                        $selected = ($entry===$currentTheme)?' selected="selected"':'';
                        echo "\t".'<option value="'.$entry.'"'.$selected.'>'.$entry.'</option>'."\r\n";
                    }
                }
                closedir($handle);
            }
            ?>
        </select>
        <p>
            <a href="?step=<?php echo $step-1; ?>" class="pwe-ui-btn">précédent</a> 
            <input class="pwe-ui-btn" type="submit" name="submit" value="Créer un compte admin" />
            <input class="pwe-ui-btn" type="submit" name="submit_end" value="Finaliser l'installation" />
        </p>
    </div>

    <div class="columns thirteen" <?php echo ($step===4)?'':'style="display: none;"'; ?>>
        <h2>&Eacute;tape 4 : Comptes de messagerie</h2>
        <p>Admin :</p>Nom : <input type="text" name="admin_name" value="<?php echo (isset($_POST)&&isset($_POST['admin_name']))?$_POST['admin_name']:''; ?>"/><br/>Mail : <input type="text" name="admin_mail" value="<?php echo (isset($_POST)&&isset($_POST['admin_mail']))?$_POST['admin_mail']:''; ?>"/><br/>
        <p>Contact :</p>Nom : <input type="text" name="contact_name" value="<?php echo (isset($_POST)&&isset($_POST['contact_name']))?$_POST['contact_name']:''; ?>"/><br/>Mail : <input type="text" name="contact_mail" value="<?php echo (isset($_POST)&&isset($_POST['contact_mail']))?$_POST['contact_mail']:''; ?>"/><br/>
        <p>Support :</p>Nom : <input type="text" name="support_name" value="<?php echo (isset($_POST)&&isset($_POST['support_name']))?$_POST['support_name']:''; ?>"/><br/>Mail : <input type="text" name="support_mail" value="<?php echo (isset($_POST)&&isset($_POST['support_mail']))?$_POST['support_mail']:''; ?>"/><br/>
        <p>Service :</p>Nom : <input type="text" name="service_name" value="<?php echo (isset($_POST)&&isset($_POST['service_name']))?$_POST['service_name']:''; ?>"/><br/>Mail : <input type="text" name="service_mail" value="<?php echo (isset($_POST)&&isset($_POST['service_mail']))?$_POST['service_mail']:''; ?>"/>
        <p>
            <a href="?step=<?php echo $step-1; ?>" class="pwe-ui-btn">précédent</a> 
            <input class="pwe-ui-btn" type="submit" name="submit" value="<?php echo $submitLabel; ?>" />
        </p>
    </div>
    
    <div class="columns thirteen" <?php echo ($step===5)?'':'style="display: none;"'; ?>>
        <h2>&Eacute;tape 5 : Ajouter un membre admin</h2>
        <br/>
        <label>Prénom : </label><input id="prenom" type="text" name="prenom" value="" /><br/>
        <label>Nom : </label><input id="nom" type="text" name="nom" value="" /><br/>
        <label>Email (login) : </label><input id="email" type="text" name="email" value="" /><br/>
        <label>Mot de passe : </label><input id="mdp" type="password" name="mdp" value="" /><br/>
            
        <a href="?step=<?php echo $step-1; ?>" class="pwe-ui-btn">précédent</a>
        <input class="pwe-ui-btn" type="submit" name="submit" value="créer mon compte admin" />
    </div>
    
    <div class="columns thirteen" <?php echo ($step===6)?'':'style="display: none;"'; ?>>
        <h2>Fin de l'installation</h2>
        <br/>
        <a href="?end_installation=1" class="pwe-ui-btn">Fin de l'installation</a>
    </div>
</form>